import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

//coding=utf8
/**
 * @Author: bighu
 * @Created Time : 2022年05月16日 星期一 16时18分03秒
 * @File Name: shiyan4_2_server.java
 * @Description:
 */

public class shiyan4_2_server {
	public static final String sorkey = "itsnotkey";
	public static void main(String[] args)throws Exception{
		//获取密钥
		String algorithm = "HmacSHA512";
		byte[] byteKey = sorkey.getBytes(StandardCharsets.UTF_8);
		//sha512Hmac 是Hmac用的密钥,会被保存起来
		Mac sha512Hmac=Mac.getInstance(algorithm);
		SecretKeySpec keySpec = new SecretKeySpec(byteKey,algorithm);
		sha512Hmac.init(keySpec);
		System.out.println("test");
		try {
			ServerSocket serversoc = new ServerSocket(8000);
			Socket soc = serversoc.accept();
			InputStream input =  soc.getInputStream();
			byte[] cliinput = new byte[input.available()];
			input.read(cliinput);
			String s = new String(cliinput, 0, cliinput.length);
			System.out.println("客户端发来消息为:" + s);
			Thread.sleep(500);
			byte[] cHmac = new byte[input.available()];
			input.read(cHmac);
			System.out.println("客户端发来HMAC为:" +Base64.getEncoder().encodeToString(cHmac));
			byte[] macData = sha512Hmac.doFinal(s.getBytes(StandardCharsets.UTF_8));
			System.out.println("本地计算HMAC为:" +Base64.getEncoder().encodeToString(macData));
			serversoc.close();
		}catch(Exception e){

			e.printStackTrace();
		}
	}

}
